package Socket;

import java.io.*;
import java.net.Socket;

public class Client {

    public static void main(String[] args) throws Exception {

        String Client_file_path = System.getProperty("user.dir") + File.separator + "ClientFiles" + File.separator;
        System.out.println("当前工作路径：" + Client_file_path);

        /*1. 指定要连接的服务器，需要同时指定服务器的IP & Port*/
        Socket cs = new Socket("127.0.0.1", 8888); //ClientSocket

        String file_name = "00.bmp"; //普通文件
        //String file_name = "1.JPG"; //测试文件名大小写
        //String file_name = "test.txt"; //测试大小为1024字节整数倍的文件，test的大小为1024字节（判断是否正常退出循环）

        /*2. 给服务器端发途数据或者接受数据*/
        OutputStream os = cs.getOutputStream();
        DataOutputStream dos = new DataOutputStream(os);
        dos.writeUTF(file_name);
        dos.flush();

        InputStream is = null;
        DataInputStream dis = null;
        FileOutputStream fos = null;

        try {
            is = cs.getInputStream();
            dis = new DataInputStream(is);
            if (dis.readBoolean()) {

                System.out.println("======== 开始接收文件 ========");

                /*接收文件长度*/
                long file_length = dis.readLong();
                File file = new File(Client_file_path + file_name);

                /*正式接收文件*/
                fos = new FileOutputStream(file);
                byte[] bytes = new byte[1024];
                int length;
                long progress = 0;

                //while ((length = dis.read(bytes, 0, bytes.length)) > 0) { //最后发送一个空的字节数组，推测可以使得该赋值语句返回值为0，该方法未成功
                //while ((length = dis.read(bytes, 0, bytes.length)) != -1) { //最后发送一个空的字节数组，推测可以使得该赋值语句返回值为-1，该方法未成功
                while (progress < file_length && (length = dis.read(bytes, 0, bytes.length)) != -1) { //判断条件不可颠倒
                    fos.write(bytes, 0, length);
                    fos.flush();
                    progress = progress + length;
                    System.out.print("传输进度：" + (100 * progress / file_length) + "%\r");
                }
                System.out.println();
                if (file.length() == file_length) {
                    System.out.println("======== 文件接收成功 ========");
                } else {
                    System.out.println("======== 文件接收失败 ========");
                }
            } else {
                System.out.println("======== 该文件不存在 ========");
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            dos.writeBoolean(true);
            dos.flush();

            /*
            dos.writeUTF(""); //发送内容为空的字符串，服务器端read后返回-1，可以作为结束循环的判断条件
            dos.flush();
            */

            if (fos != null)
                fos.close();
            if (dis != null)
                dis.close();
        }

        /*3. 释放资源*/
        os.close();
        if (is != null) {
            is.close();
        }
        cs.close();

    }

}